package com.caoji.web;

import com.caoji.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @Description： User: caoji
 * Date: 2020/11/26
 * Time: 19:40
 */
@RestController
@RequestMapping("/com")
public class comcontrller {
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryfallback")
    public User list(@PathVariable("id")String name){
//        String url="http://localhost:8081/user/list/"+name;
//        Map userMap = restTemplate.getForObject(url, Map.class);
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url = serviceInstance.getUri().toString();\
        String url = "http://user-service/user/list/" + name; // user-service 微服务名称
        if("caoji".equals(name)){
            throw new RuntimeException("caoji");
        }
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    public User queryfallback(String id){
        User user=new User();
        user.setName("暂停服务");
        return user;
    }
}
